<template>
  <div class="scatter-plot-panel">
    <div class="header-bar">
      <div class="left-section">
        <span v-if="collectionTime" class="collection-time">
          采集时间：{{ collectionTime }}
        </span>
      </div>
      <div class="right-section">
        <el-button v-if="isFullscreen" type="primary" @click="exitFullscreen" :loading="loading">
          <el-icon><Close /></el-icon>
          退出全屏
        </el-button>
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>
    <div class="chart-wrapper" v-loading="loading">
      <div ref="chartContainer" class="chart-container"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { Refresh, Close } from '@element-plus/icons-vue'
import { useDeviceStore } from '@/stores/deviceStore'

const deviceStore = useDeviceStore()
const chartContainer = ref(null)
const loading = ref(false)
const collectionTime = ref('') // 采集时间
const isFullscreen = ref(false) // 全屏状态
let chart = null // 图表实例变量

// 处理全屏变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement
}

// 退出全屏
const exitFullscreen = async () => {
  try {
    if (document.fullscreenElement) {
      await document.exitFullscreen()
    }
  } catch (error) {
    // console.error('退出全屏失败:', error)
    ElMessage.error('退出全屏失败')
  }
}

// 获取图表数据
const fetchChartData = async () => {
  if (!deviceStore.currentDevice) {
    // console.warn('当前没有选中设备')
    return
  }

  loading.value = true
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未找到登录令牌')
    }

   const deviceId = deviceStore.currentDevice.id.toString();
   if (!deviceId) {
     throw new Error('无效的设备 ID');
   }

   const response = await fetch(`https://penglink.pcwxcn.top/api/dashboard/chart/acquisition/${deviceId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`)
    }

    const result = await response.json()
    if (result.code !== 200 || !result.data || !result.data.chart_data) {
      throw new Error(result.msg || '获取数据失败')
    }

    const { points = [], times = [], x = [], y = [] } = result.data.chart_data

    // 验证数据完整性
    if (!Array.isArray(x) || !Array.isArray(y)) {
      throw new Error('数据格式不正确')
    }

    if (x.length === 0 || y.length === 0) {
      throw new Error('数据为空')
    }

    if (x.length !== y.length) {
      throw new Error('X轴和Y轴数据长度不匹配')
    }
    
    // 反转x和y数组，因为接口返回的数据顺序是反的
    const reversedX = [...x].reverse()
    const reversedY = [...y].reverse()

    // 更新采集时间
    collectionTime.value = times?.[0] || ''

    // 获取点数限制并验证
    const pointLimit = Math.min(parseInt(points[0]) || reversedX.length, reversedX.length)

    // 数据预处理
    const processedData = reversedX.slice(0, pointLimit).map((xVal, index) => {
      const xNum = parseFloat(xVal) / 100
      const yNum = parseFloat(reversedY[index]) / 100
      
      if (isNaN(xNum) || isNaN(yNum)) {
        // console.warn(`无效的数据点: x=${xVal}, y=${reversedY[index]}`)
        return null
      }

      return {
        value: [xNum, yNum],
        index
      }
    }).filter(point => point !== null)

    if (processedData.length === 0) {
      throw new Error('没有有效的数据点')
    }

    // 计算数据范围
    const xValues = processedData.map(d => d.value[0])
    const yValues = processedData.map(d => d.value[1])
    const xMin = Math.min(...xValues)
    const xMax = Math.max(...xValues)
    const yMin = Math.min(...yValues)
    const yMax = Math.max(...yValues)

    // 更新图表配置
    const option = {
      animation: false,
      grid: {
        top: '10%',
        left: '10%',
        right: '5%',
        bottom: '15%',
        containLabel: true
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          return `位移: ${(params.value[0] || 0).toFixed(2)} m<br/>载荷: ${(params.value[1] || 0).toFixed(2)} kN<br/>序号: ${(params.dataIndex || 0) + 1}`
        }
      },
      xAxis: {
        type: 'value',
        name: '位移 (m)',
        nameLocation: 'center',
        nameGap: 30,
        min: xMin - Math.abs(xMin * 0.1),
        max: xMax + Math.abs(xMax * 0.1),
        axisLabel: {
          fontSize: 10,
          formatter: (value) => value.toFixed(2)
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#EBEEF5'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '载荷 (kN)',
        nameLocation: 'center',
        nameGap: 45,
        min: yMin - Math.abs(yMin * 0.1),
        max: yMax + Math.abs(yMax * 0.1),
        axisLabel: {
          fontSize: 10,
          formatter: (value) => value.toFixed(2)
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#EBEEF5'
          }
        }
      },
      series: [{
        type: 'scatter',
        symbolSize: 6,
        itemStyle: {
          color: '#409EFF',
          opacity: 0.8
        },
        emphasis: {
          itemStyle: {
            color: '#409EFF',
            opacity: 1,
            borderColor: '#fff',
            borderWidth: 1
          }
        },
        data: processedData
      }]
    }

    // 更新图表
    if (chart) {
      chart.setOption(option, true)
      chart.resize()
    }
  } catch (error) {
    // console.error('获取图表数据失败:', error)
    ElMessage.error(error.msg || error.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateChart = (data, ranges = null) => {
  if (!chart) {
    // console.warn('图表实例不存在')
    return
  }

  // 验证数据格式
  const validData = Array.isArray(data) && data.length === 2
  if (!validData) {
    // console.warn('数据格式无效')
    return
  }

  const firstHalf = data[0] || []
  const secondHalf = data[1] || []

  // 验证数据点
  if (firstHalf.length === 0 && secondHalf.length === 0) {
    // console.warn('没有有效的数据点')
    return
  }

  const option = {
    animation: false,
    grid: {
      top: '10%',
      left: '10%',
      right: '5%',
      bottom: '15%',
      containLabel: true
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        const data = params.data || {}
        return `位移: ${data.x?.toFixed(2) || '0.00'} m<br/>载荷: ${data.y?.toFixed(2) || '0.00'} kN<br/>序号: ${(data.index || 0) + 1}`
      }
    },
    xAxis: {
      type: 'value',
      name: '位移 (m)',
      nameLocation: 'center',
      nameGap: 30,
      min: ranges?.xMin,
      max: ranges?.xMax,
      axisLabel: {
        fontSize: 10,
        formatter: (value) => value.toFixed(2)
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: '#EBEEF5'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '载荷 (kN)',
      nameLocation: 'center',
      nameGap: 45,
      min: ranges?.yMin,
      max: ranges?.yMax,
      axisLabel: {
        fontSize: 10,
        formatter: (value) => value.toFixed(2)
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: '#EBEEF5'
        }
      }
    },
    series: [
      {
        name: '前半部分',
        type: 'scatter',
        symbolSize: 6,
        itemStyle: {
          color: '#67C23A',
          opacity: 0.8
        },
        emphasis: {
          itemStyle: {
            color: '#67C23A',
            opacity: 1,
            borderColor: '#fff',
            borderWidth: 1
          }
        },
        data: firstHalf
      },
      {
        name: '后半部分',
        type: 'scatter',
        symbolSize: 6,
        itemStyle: {
          color: '#409EFF',
          opacity: 0.8
        },
        emphasis: {
          itemStyle: {
            color: '#409EFF',
            opacity: 1,
            borderColor: '#fff',
            borderWidth: 1
          }
        },
        data: secondHalf
      }
    ]
  }

  try {
    chart.setOption(option, true)
    chart.resize()
  } catch (error) {
    // console.error('更新图表失败:', error)
    ElMessage.error('更新图表失败')
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

// 刷新数据
const refreshData = () => {
  fetchChartData()
}

// 初始化图表实例
const initChart = () => {
  if (!chartContainer.value) {
    // console.warn('图表容器不存在')
    return
  }

  // 设置容器尺寸
  chartContainer.value.style.width = '100%'
  chartContainer.value.style.height = '100%'

  // 如果已存在实例，先销毁
  if (chart) {
    chart.dispose()
  }

  // 创建新实例
  try {
    chart = echarts.init(chartContainer.value)
    // 设置基础配置
    chart.setOption({
      animation: false,
      grid: {
        top: '10%',
        left: '10%',
        right: '5%',
        bottom: '15%',
        containLabel: true
      },
      tooltip: {
        show: true,
        trigger: 'item',
        formatter: function(params) {
          return `位移: ${params.data?.x?.toFixed(2) || 0} m<br/>载荷: ${params.data?.y?.toFixed(2) || 0} kN<br/>序号: ${(params.data?.index || 0) + 1}`
        }
      },
      xAxis: {
        type: 'value',
        name: '位移 (m)',
        nameLocation: 'center',
        nameGap: 30,
        axisLabel: {
          fontSize: 10,
          formatter: (value) => value.toFixed(2)
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#EBEEF5'
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '载荷 (kN)',
        nameLocation: 'center',
        nameGap: 45,
        axisLabel: {
          fontSize: 10,
          formatter: (value) => value.toFixed(2)
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#EBEEF5'
          }
        }
      },
      series: []
    })
    return true
  } catch (error) {
    // console.error('初始化图表失败:', error)
    ElMessage.error('初始化图表失败')
    return false
  }
}

// 定时器引用
let timer = null

// 生命周期钩子
onMounted(() => {
  // 确保DOM已经渲染完成
  nextTick(async () => {
    // 初始化图表
    if (initChart()) {
      // 添加事件监听
      window.addEventListener('resize', handleResize)
      document.addEventListener('fullscreenchange', handleFullscreenChange)
      
      // 获取初始数据
      await fetchChartData()

      // 设置定时刷新，增加间隔到60秒，减少API请求频率
      timer = setInterval(fetchChartData, 60000)
    }
  })
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
  window.removeEventListener('resize', handleResize)
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style scoped>
.scatter-plot-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
  background-color: #fff;
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 16px;
  background-color: #fff;
  border-bottom: 1px solid #EBEEF5;
  margin: 0;
  height: 32px;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.collection-time {
  font-size: 12px;
  color: #606266;
}

:deep(.el-button) {
  padding: 4px 12px;
  height: 24px;
  font-size: 12px;
}

:deep(.el-icon) {
  font-size: 12px;
}

.chart-wrapper {
  flex: 1;
  position: relative;
  min-height: 200px;
  overflow: hidden;
  background-color: #fff;
  padding: 0 16px 16px;
}

.chart-container {
  width: 100%;
  height: 100%;
}

@media screen and (max-width: 768px) {
  .scatter-plot-panel {
    min-height: 300px;
  }

  .header-bar {
    flex-direction: row;
    padding: 4px 12px;
  }

  .left-section {
    flex-direction: row;
    align-items: center;
  }
}

:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.9);
}
</style>